package indi.jp.project.business.device.service.impl;

import indi.jp.project.business.device.dao.DevicePurchaseDAO;
import indi.jp.project.center.service.TaskService;
import indi.jp.project.core.entity.Datagrid;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.util.SerialUtil;
import indi.jp.project.process.entity.FlowTaskNotifyDTO;
import indi.jp.project.process.service.FlowTaskService;
import indi.jp.project.business.device.entity.DevicePurchase;
import indi.jp.project.business.device.service.DevicePurchaseService;
import indi.jp.project.business.device.service.DeviceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("devicePurchaseService")
public class DevicePurchaseServiceImpl implements DevicePurchaseService {

    @Resource
    private DevicePurchaseDAO devicePurchaseDAO;

    @Resource
    private DeviceService deviceService;

    @Resource
    private TaskService taskService;

    @Resource
    private SerialUtil serialUtil;

    @Resource
    private FlowTaskService flowTaskService;

    @Override
    public JsonResult queryGrid(DevicePurchase entity) throws Exception {
        List<DevicePurchase> list = devicePurchaseDAO.queryList(entity);
        int count = devicePurchaseDAO.queryCount(entity);
        Datagrid<DevicePurchase> datagrid = new Datagrid<>(list, count);
        return JsonResult.success(datagrid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult save(DevicePurchase entity) throws Exception {
        String id;
        if (StringUtils.isBlank(entity.getId())) {
            id = String.valueOf(serialUtil.nextId());
            entity.setId(id);
            devicePurchaseDAO.insert(entity);
        } else {
            id = entity.getId();
            devicePurchaseDAO.update(entity);
        }
        flowTaskService.saveTaskFlow(id, entity.getFlowList());
        return JsonResult.success("保存成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult deleteById(String id) throws Exception {
        devicePurchaseDAO.deleteById(id);
        flowTaskService.deleteFlowByTaskId(id);
        return JsonResult.success("删除成功");
    }

    @Override
    public JsonResult findById(String id) throws Exception {
        DevicePurchase devicePurchase = devicePurchaseDAO.findById(id);
        return JsonResult.success(devicePurchase);
    }

    @Override
    public void notify(FlowTaskNotifyDTO flowTaskNotifyDTO) throws Exception {
        if (flowTaskNotifyDTO.getNextState() == 99) {
            DevicePurchase devicePurchase = devicePurchaseDAO.findById(flowTaskNotifyDTO.getTaskId());
            deviceService.newPurchaseDevice(devicePurchase);
        }
    }
}
